# 防火墙服务
# 循环检测是否有新的防火墙规则
# 如果有新的规则，则更新防火墙规则
# 定时检测防火墙规则是否过期，如果过期，则删除防火墙规则
import logging
import threading
import time

from fastapi import FastAPI

from lib import Config, LoginLoger
from lib.FireWallManager import FireWallManager

app = FastAPI()

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    filename='firewall.log')


class FWService:
    def __init__(self):
        self.fw = FireWallManager()
        self.ip_list_lock = threading.Lock()
        self.ip_list = []
        self.fw_rules_expire_thread = threading.Thread(target=self.fw_rules_expire_thread_func)
        self.fw_rules_expire_thread.start()

    def fw_rules_expire_thread_func(self):
        self.fw.init_established_ips()
        t_start = time.time()
        while True:
            time.sleep(0.01)
            if len(self.ip_list) > 0:
                self.ip_list_lock.acquire()
                while len(self.ip_list) > 0:
                    obj = self.ip_list.pop()
                    try:
                        self.fw.add_ip_rule(obj['ip'])
                        LoginLoger.push_user_login_log(obj['uid'], obj['ip'])
                    except Exception as e:
                        logging.error('add ip rule error %s', e)
                self.ip_list_lock.release()
            t_now = time.time()
            if t_now - t_start > Config.AutoFlushTime:
                logging.info('time out, check expire')
                self.fw.init_established_ips()
                t_start = t_now

    def add_ip(self, ip, uid=0):
        self.ip_list_lock.acquire()
        self.ip_list.append({"ip": ip, "uid": uid})
        self.ip_list_lock.release()


fw_service = FWService()


@app.get('/api/push_ip')
def add_ip(ip, uid=0):
    logging.info('http api add ip: %s', ip)
    fw_service.add_ip(ip, uid)
    return {"code": 0, "msg": 'success', "data": {"uid": uid, "ip": ip}}
